/*
 *    Description: oray
 *          Author:  dimmalex (dim), dimmalex@gmail.com
 *      Company:  HP
 */

#include "land/farm.h"
#define ORAY_LOG_INFO_FILE "/etc/config/init.status"



const char *_intro( obj_t this )
{
    const char *str = \
"{"\
"\n    \"setup\":\"setup the oray\","\
"\n    \"shut\":\"shutdown the oray\","\
"\n    \"info\":\"get the oray info\","\
"\n    \"reset\":\"rest the oray\""\
"\n}\n";
    return str;
}
talk_t _setup( obj_t this, param_t param )
{
    talk_t cfg;
    const char *ptr;

    cfg = config_sget( COM_IDPATH, NULL );
    ptr = json_get_string( cfg, "status" );
    if ( ptr == NULL || 0 != strcmp( ptr, "enable" ) )
    {
        talk_free( cfg );
        return tfalse;
    }
    serv_start( this, "service", NULL, "%s-%s", PROJECT_ID, COM_ID );
    talk_free( cfg );
    return ttrue;
}
talk_t _shut( obj_t this, param_t param )
{
    serv_stop( "%s-%s", PROJECT_ID, COM_ID );
    shell( "killall -9 oraysl" );
    return ttrue;
}
talk_t _service( obj_t this, param_t param )
{
    shell( "oraysl -a 127.0.0.1 -p 16062 -s phsle01.oray.net:80 -d" );
    execlp( "oraynewph", "oraynewph", "-s", "0.0.0.0", "&", (char*)0 );
    wrong( "execlp the oraynewph error" );
    return tfalse;
}
talk_t _info( obj_t this, param_t param )
{
    FILE *fp;
    talk_t talk_info;
    char buf[1024];

    talk_info = json_create();
    json_set_string( talk_info, "sn", "" );
    json_set_string( talk_info, "status", "" );
    fp = fopen("/tmp/oraysl.status", "rt");
    if ( NULL == fp )
    {
        return NULL;
    }
    while( NULL != fgets( buf, sizeof(buf), fp ))
    {
        buf[strlen(buf) - 1] = '\0';
        if( strstr(buf, "sn=") )
        {
            json_set_string( talk_info, "sn", buf+3 );
        }
        if( strstr(buf, "status=") )
        {
            json_set_string( talk_info, "status", buf+7 );
        }
    }
    fclose( fp );
    return talk_info;
}
talk_t _reset( obj_t this, param_t param )
{
    if ( 0 == access( ORAY_LOG_INFO_FILE, 0 ) )
    {
        if ( 0 == unlink( ORAY_LOG_INFO_FILE ) )
        {
            return ttrue;
        }
    }
    return tfalse;
}



boole _set( obj_t this, path_t path, talk_t v )
{
    obj_t o;
    boole ret;

    o = obj_create( COM_IDPATH );
    ret = config_set( o, path, v );
    if ( ret == true )
    {
        _shut( this, NULL );
        _setup( this, NULL );
    }
    obj_free( o );
    return ret;
}
talk_t _get( obj_t this, path_t path )
{
    obj_t o;
    talk_t ret;

    o = obj_create( COM_IDPATH );
    ret = config_get( o, path );
    obj_free( o );
    return ret;
}



